/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClickHappinessEditor.java
 *
 * Created on 2011-12-11, 11:25:12
 */
package pobicos;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author marcin
 */
public class ClickHappinessEditor extends javax.swing.JDialog {

    private JTable table_;
    private DefaultTableModel tableModel_;
    private Agent agentNode_;
    private JungTreePanel graphicTree_;
    
    private int instancesCounter_=1;
    private int numberOfInstaces=0;

    /** Creates new form ClickHappinessEditor */
    public ClickHappinessEditor(JungTreePanel graphicTree) {
        super(graphicTree.getMainViewFrame(), true);
        graphicTree_ = graphicTree;
        this.setLocationRelativeTo(graphicTree_.getMainViewFrame());
        initComponents();
        agentNode_ = (Agent) graphicTree_.getLogicalTree().getNodeAt(graphicTree_.currentPickedVertex).getData();
        if(agentNode_.isMultilpe()) {
            numberOfInstaces = agentNode_.getNumberOfInstances();
        }
        initTable();
    }

    private void initTable() {
        mainPanel.setLayout(new FlowLayout());
        String[] columns = {"Goal", "Happiness"};
        String[][] rows = new String[agentNode_.getType().getGoalsList().size()][2];
        for (int i = 0; i < agentNode_.getType().getGoalsList().size(); i++) {
            rows[i][0] = agentNode_.getType().getGoalsList().get(i);
        }
        tableModel_ = new DefaultTableModel(rows, columns) {

            @Override
            public boolean isCellEditable(int row, int column) {
                if (column == 0) {
                    return false;
                }
                return super.isCellEditable(row, column);
            }
        };
        if (agentNode_.getHappinessMap() != null) {
            for (int i = 0; i < tableModel_.getRowCount(); i++) {
                tableModel_.setValueAt(agentNode_.getHappinessMap().get((String) tableModel_.getValueAt(i, 0)), i, 1);
            }
        }
        tableModel_.addTableModelListener(new TableModelListener() {

            public void tableChanged(TableModelEvent e) {
                int row = e.getFirstRow();
                int column = e.getColumn();
                TableModel model = (TableModel) e.getSource();
                try {
                    Double d = Double.parseDouble(model.getValueAt(row, column).toString());
                    if (d < 0.0 || d > 1.0) {
                        throw new IndexOutOfBoundsException();
                    }
                } catch (NumberFormatException w) {
                    model.setValueAt(0.0, row, column);
                    JOptionPane.showMessageDialog(null, "Incorrect number format!");
                } catch (IndexOutOfBoundsException w) {
                    model.setValueAt(0.0, row, column);
                    JOptionPane.showMessageDialog(null, "The value must be betwenn value 0.0 and 1.0!");
                }
            }
        });
        table_ = new JTable(tableModel_);
        table_.setPreferredScrollableViewportSize(mainPanel.getSize());
        table_.setFillsViewportHeight(true);
        mainPanel.add(new JScrollPane(table_));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        title = new javax.swing.JLabel();
        closeButton = new javax.swing.JButton();
        enterButton = new javax.swing.JButton();
        mainPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(pobicos.AdaptSysApp.class).getContext().getResourceMap(ClickHappinessEditor.class);
        title.setFont(resourceMap.getFont("title.font")); // NOI18N
        title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        title.setText(resourceMap.getString("title.text")); // NOI18N
        title.setName("title"); // NOI18N

        closeButton.setText(resourceMap.getString("closeButton.text")); // NOI18N
        closeButton.setName("closeButton"); // NOI18N
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        enterButton.setText(resourceMap.getString("enterButton.text")); // NOI18N
        enterButton.setName("enterButton"); // NOI18N
        enterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enterButtonActionPerformed(evt);
            }
        });

        mainPanel.setName("mainPanel"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 236, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 175, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(mainPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(title, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(enterButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 118, Short.MAX_VALUE)
                        .addComponent(closeButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(title, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton)
                    .addComponent(enterButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enterButtonActionPerformed

        if (!agentNode_.isMultilpe()) {
            Map<String, Double> tempMap = new HashMap<String, Double>();
            for (int i = 0; i < agentNode_.getType().getGoalsList().size(); i++) {
                tempMap.put(tableModel_.getValueAt(i, 0).toString(), Double.parseDouble(tableModel_.getValueAt(i, 1).toString()));
            }
            agentNode_.setHappinessMap(tempMap);
            graphicTree_.getPickedState().clear();
            dispose();
        } else {
            
            Map<String, Double> tempMap = new HashMap<String, Double>();
            for (int i = 0; i < agentNode_.getType().getGoalsList().size(); i++) {
                tempMap.put(tableModel_.getValueAt(i, 0).toString(), Double.parseDouble(tableModel_.getValueAt(i, 1).toString()));
            }
            agentNode_.getInstacesHappMap().put(instancesCounter_++, tempMap);     
     
            //=================================
            if (instancesCounter_ <= numberOfInstaces) {
                title.setText("Enter happiness level for "+ instancesCounter_);
                
            } else {
                agentNode_.setHappinessMap(agentNode_.getInstacesHappMap().get(2));
                graphicTree_.getPickedState().clear();
                dispose();
            }
        }
    }//GEN-LAST:event_enterButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JButton enterButton;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JLabel title;
    // End of variables declaration//GEN-END:variables
}
